package org.hshk.message.controller;

import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.hshk.message.BaseController;
import org.hshk.message.entity.CpMsgFactory;
import org.hshk.message.repository.CpMsgFactoryRepository;
import org.hshk.message.service.CpMsgFactoryService;
import org.hshk.message.utils.HttpClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by GaoChuang on 2017/3/28.
 */
 @Api(value = "短信厂商 API")
@RestController
@RequestMapping("/factorys")


 //短信厂商查询
public class MsgFactoryQueryController extends BaseController{
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(MsgFactoryQueryController.class);
    @Autowired
    private CpMsgFactoryService service;
    @Autowired
    //查询短信厂商的 单表查询对象
    CpMsgFactoryRepository cpMsgFactoryRepository;
    //线程保存对象
    private ThreadLocal<Gson> local = new ThreadLocal<Gson>();
    //对象存放类
    private Gson getGson()
    {
        if(null == local.get())
        {
            Gson gson = new Gson();
            local.set(gson);
        }
        return local.get();
    }

    @ApiOperation(value = "获取短信厂商")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)

    //这是查询所有短信厂商的方法
    public String query()
    {
        try
        {
            return getGson().toJson(service.getFactories());
        }catch(Exception ex)
        {
            log.error("MsgFactoryQuery.query " + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }
    @ApiOperation(value = "根据id获取短信厂商名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "factoryId", value = "短信厂商id", required = true, dataType = "int", paramType = "path"),
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/factoryId/{factoryId}", method = RequestMethod.GET, produces = "application/json")

    public String msgFactoryName(@PathVariable int factoryId) {
        try {
            log.info("MsgFactoryQuery.msgFactoryName " + "短信厂商id" + factoryId);
            Map<String, Object> paramMsg = new HashMap<>();
            if (0 == factoryId) {
                paramMsg.put("factoryId", "参数不对");
            }
            if (0 != paramMsg.size()) {
                return getGson().toJson(paramMsg);
            }

            CpMsgFactory cpMsgFactory;
            cpMsgFactory = cpMsgFactoryRepository.findById(factoryId);
            return getGson().toJson(cpMsgFactory.getFactoryName());
        } catch (Exception ex) {
            log.error("MsgFactoryQuery.msgFactoryName " + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }

    /**
     * 2017年5月15日09:33:54
     * GaoChuang
     * 根据brandId ,msgUsername和msgPassword查询账号是不是出错
     */
    @ApiOperation(value = "根据brandId ,msgUsername和msgPassword查询短信账号是否出错")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "msgFacturer", allowableValues = "互亿无线,光通互动", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "msgUserName", value = "账号", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "msgPassWord", value = "密码", required = true, dataType = "String", paramType = "path")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping( value = "/msgFacturer/{msgFacturer}/msgUserName/{msgUserName}/msgPassWord/{msgPassWord}", method = RequestMethod.GET, produces = "application/json")

    //根据短信厂商id，用户名，密码，查询账号是否有异常
    public String memberSignAccountInformation(@PathVariable("msgFacturer")String msgFacturer, @PathVariable("msgUserName") String msgUserName, @PathVariable("msgPassWord") String msgPassWord) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try{
            if(null == msgFacturer || "".equals(msgFacturer)){
                resultMap.put("msgFacturer", "为必填参数");
            }
            if(null == msgUserName || "".equals(msgUserName)){
                resultMap.put("msgUsername", "为必填参数");
            }
            if(null == msgPassWord || "".equals(msgPassWord)){
                resultMap.put("msgPassWord", "为必填参数");
            }
            if(0 != resultMap.size()){
                return  getGson().toJson(resultMap);
            }

            if("互亿无线".equals(msgFacturer)){
                //这个对象调用的方法，创建了一个（短信厂商）单实例对象
                HttpClient client = HttpClientFactory.getInstance();
                PostMethod method = new PostMethod("http://121.199.16.178/webservice/sms.php?method=GetNum");
                client.getParams().setContentCharset("UTF-8");
                method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
                NameValuePair[] data = {//提交短信
                        new NameValuePair("account", msgUserName),
                        new NameValuePair("password", msgPassWord), //密码可以使用明文密码或使用32位MD5加密
                };
                method.setRequestBody(data);
                client.executeMethod(method);
                String SubmitResult = method.getResponseBodyAsString();
                Document doc = DocumentHelper.parseText(SubmitResult);
                Element root = doc.getRootElement();
                if("2".equals(root.elementText("code").trim())){
                    resultMap.put("code","sucess");
                }else{
                    resultMap.put("code","fail");
                }
            }

            if("光通互动".equals(msgFacturer)){
                HttpClient client = HttpClientFactory.getInstance();
                //POST方式发送
                PostMethod method = new PostMethod("http://ganiu.guangtongcloud.com:7862/sms");
                method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
                client.getParams().setContentCharset("UTF-8");
                NameValuePair[] data = {//查询短信参数
                        new NameValuePair("action", "overage"),
                        new NameValuePair("account", msgUserName),
                        new NameValuePair("password", msgPassWord),
                };
                method.setRequestBody(data);
                client.executeMethod(method);
                String SubmitResult = method.getResponseBodyAsString();
                Document doc = DocumentHelper.parseText(SubmitResult);
                Element root = doc.getRootElement();
                if("Sucess".equals(root.elementText("returnstatus").trim())){
                    resultMap.put("code","sucess");
                }else{
                    resultMap.put("code","fail");
                }
            }

            return  getGson().toJson(resultMap);
        }catch(Exception e){
            System.err.println(e.getMessage());
            return getGson().toJson(e.getMessage());
        }
    }


}
